<template>
  <!-- 图片预览 -->
  <el-image-viewer
    v-if="imageViewerVisible"
    :url-list="imagePreviews"
    :initial-index="previewIndex"
    @close="imageViewerVisible = false"
  />
  <div class="parent">
    <!-- 返回按钮 -->
    <div class="back">
      <el-button @click="handleBack" class="icon-close"><el-icon><Back /></el-icon></el-button>
    </div>
    <el-scrollbar class="information-scroll">
      <div class="information">
        <!-- model、dealer -->
        <div class="text-border1">
          <div class="text1"><span class="text-label">Model:</span>{{ resultData.model }}</div>
          <div class="text1"><span class="text-label">Dealer:</span>{{ resultData.dealer }}</div>
        </div>
        <!-- typeButton -->
        <div class="text-border2">
          <el-button 
            :class="{ 'active': selectedType === 1 }" 
            @click="selectType(1)"
          >Operation instructions</el-button>
          <el-button 
            :class="{ 'active': selectedType === 2 }" 
            @click="selectType(2)"
          >Installation Instructions</el-button>
          <el-button 
            :class="{ 'active': selectedType === 3 }" 
            @click="selectType(3)"
          >Remote control instructions</el-button>
        </div>
        
        <!-- 动态显示当前选中类型的数据 -->
        <template v-if="currentModelData">
          <!-- title -->
          <div class="text-border2">
            <span class="text-label">Title:</span>
            <el-input
              v-model="currentModelData.title"
              placeholder="Please enter the title"
              class="title-input"
            />
          </div>
          <!-- content -->
          <div class="text-border3">
            <span class="text-label">Content:</span>
            <el-input
              v-model="currentModelData.content"
              placeholder="Please enter the content"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 6 }"
              class="content-input"
              resize="none"
            />
          </div>
          <!-- img -->
          <div class="text-border4">
            <span class="text-label">Image:</span>
            <div class="images-wrapper">
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :multiple="selectType !== 3"
                :limit="selectedType === 3 ? 1 : 10"
                :on-change="handleImageChange"
                :on-remove="handleImageRemove"
                :file-list="currentModelData.imageFiles || []"
                accept="image/*"
                :on-preview="handlePictureCardPreview"
                :on-exceed="handleExceed"
              >
                <el-icon><Plus /></el-icon>Add pictures
              </el-upload>
            </div>
          </div>
          <!-- video -->
          <div class="text-border5" v-if="selectedType !== 3">
            <span class="text-label">Video:</span>
            <div class="video-wrapper">
              <el-upload
                v-if="!currentModelData.videoPreviewUrl"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleVideoChange"
                accept="video/*"
                :disabled="videoUploading"
              >
                <el-button type="primary" :loading="videoUploading" class="video-button">
                  <el-icon><Plus /></el-icon>Add video
                </el-button>
              </el-upload>
              <div v-if="currentModelData.videoPreviewUrl" class="video-preview-container">
                <video 
                  controls
                  class="video-preview"
                  :src="currentModelData.videoPreviewUrl"
                >Your browser does not support video playback.</video>
                <div class="video-actions">
                  <el-button 
                    type="danger" 
                    @click="handleVideoRemove"
                    :loading="videoUploading"
                  >
                    Delete video
                  </el-button>
                </div>
              </div>     
            </div>
          </div>
          <!-- 提交 -->
          <div class="text-border6">
            <el-button type="primary" @click="handleEditMessage">Submit</el-button>
            <el-button type="danger" @click="handleDeleteMessage" :disabled="!currentModelData?.id">Delete</el-button>
          </div>
        </template>
        <div v-else class="no-data-tip">
          Please select the type of instructions first.
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
  import { ref, onMounted, computed } from 'vue'
  import { ElMessage, ElImageViewer,ElMessageBox } from 'element-plus';
  import { Plus, Back } from '@element-plus/icons-vue'
  import {compressImg} from '../../utils';
  import { useLoading } from '../../utils/loading';
  import axios from 'axios';
  const { showLoading, hideLoading } = useLoading();
  const BASE_URL = import.meta.env.VITE_API_URL;

  const props = defineProps({
    ModelData: {
      type: Object,
      default: null
    }
  })

  const modelData = ref(props.ModelData)
  const emit = defineEmits(['back', 'status-updated']);

  // type变量
  const selectedType = ref(null);
  // 图片变量
  const imageViewerVisible = ref(false)
  const previewIndex = ref(0)
  const imagePreviews = ref([])
  // 视频变量
  const videoUploading = ref(false)

  // 处理后的数据
  const resultData = computed(() => {
    return {...modelData.value}
  })

  // 改为数组形式，包含三种类型的数据
  const modelsData = ref([
    {
      type: 1,
      id: null,
      title: '',
      content: '',
      key:'',
      imgUrl: '',
      videoUrl: '',
      imageFiles: [],
      videoPreviewUrl: ''
    },
    {
      type: 2,
      id: null,
      title: '',
      content: '',
      key:'',
      imgUrl: '',
      videoUrl: '',
      imageFiles: [],
      videoPreviewUrl: ''
    },
    {
      type: 3,
      id: null,
      title: '',
      content: '',
      key:'',
      imgUrl: '',
      videoUrl: '',
      imageFiles: [],
      videoPreviewUrl: ''
    }
  ])

  // 当前选中的模型数据
  const currentModelData = computed(() => {
    return modelsData.value.find(item => item.type === selectedType.value)
  })

  function handleBack() {
    emit('back');
  }

  onMounted(() => {
    if(resultData.value) {
      getModel()
    }
    // 设置默认显示type1
    selectedType.value = 1;
  }) 

  // 获取型号信息
  const getModel = async() => {
    try {
      showLoading('Loading model data...')
      const res = await axios.get(`${BASE_URL}manage/introductionList`, {
        params: {
          dealer: resultData.value.dealer,
          model: resultData.value.model,
        }
      })
      // 重置所有模型数据
      modelsData.value = modelsData.value.map(item => ({
        ...item,
        videoPreviewUrl: '',
        videoUrl: '',
        key: ''
      }))
      if(!res.data.data[0].type){
          res.data.data[0].type = 1;
        }
      // 将获取的数据分配到对应的类型
      if (res.data.data && Array.isArray(res.data.data)) {
        res.data.data.forEach(item => {
          const index = modelsData.value.findIndex(m => m.type === item.type)
          if (index !== -1) {
            modelsData.value[index] = {
              ...modelsData.value[index],
              ...item,
              imageFiles: item.imgUrl 
                          ?item.imgUrl.split(',').map(url => ({ 
                            name: url.split('/').pop(), 
                            url,
                            status: 'success' 
                          }))  
                          : [],
              videoPreviewUrl: item.videoUrl || ''
            }
          }
        })
      }
    } catch(error) {
      ElMessage.error(error.msg)
    } finally {
      hideLoading()
    }
  }

  // 修改按钮
  const handleEditMessage = async() => {
    if (!selectedType.value) {
      ElMessage.warning('Please select the type of description first.')
      return
    }

    const currentData = currentModelData.value
    if (!currentData) return

    try {
      showLoading("Submitting data...")
      //构建json数据
      const jsonData = {
        model: resultData.value.model,
        dealer: resultData.value.dealer,
        type: currentData.type,
        title: currentData.title,
        content: currentData.content, 
        imgUrl: currentData.imageFiles  
          .filter(file => file.status === 'success')
          .map(file => file.url)
          .join(','),
        videoUrl: currentData.videoPreviewUrl || '',
        id: currentData.id || null,
      }
      //根据id判断是新增还是修改
      const url = currentData.id? `${BASE_URL}manage/updateIntroduction` : `${BASE_URL}manage/addIntroduction`;
      const res = await axios.post(url, jsonData, {
        headers: {
          'Content-Type': 'application/json', // 明确指定 JSON 格式
        },
      });
      if(res.data.code === 0) {
        ElMessage.success('Submitted successfully')
        // 更新本地数据
        const index = modelsData.value.findIndex(item => item.type === selectedType.value)
        if (index !== -1) {
          modelsData.value[index] = {
            ...modelsData.value[index],
            ...currentData
          }
        }
      } else {
        ElMessage.error(res.data.msg + 'Submission failed')
      }
    } catch(error) {
      ElMessage.error(error.res?.data?.msg || 'Submission failed')
    } finally {
      hideLoading()
    }
  }
  //删除方法
  const handleDeleteMessage = async() => {
    try {
      await ElMessageBox.confirm(
        'Are you sure you want to delete this information?',
        'Deletion confirmation',
        {
          confirmButtonText: 'confirm',
          cancelButtonText: 'Cancel',
          type: 'warning',
          // 可以添加自定义类名
          customClass: 'delete-confirm-box'
        }
      )
      showLoading("Deleting...")
      const res = await axios.delete(`${BASE_URL}manage/delIntroduction/${currentModelData.value.id}`)
      if(res.data.code === 0){
        ElMessage.success('Delete successfully');
      }
    } catch(error) {
    } finally {
      hideLoading()
    }
  };

  const selectType = (type) => {
    selectedType.value = type
    // 重置图片预览
    if (currentModelData.value) {
      imagePreviews.value = currentModelData.value.imageFiles.map(item => item.url)
    }
  }

  // 图片预览处理
  const handlePictureCardPreview = (file) => {
    if (!currentModelData.value) return
    // 确保使用当前文件列表中的所有有效URL
    imagePreviews.value = currentModelData.value.imageFiles
      .filter(item => item.url)
      .map(item => item.url);
    
    // 查找当前点击图片的索引
    previewIndex.value = currentModelData.value.imageFiles.findIndex(
      item => item.uid === file.uid || item.url === file.url
    );
    
    // 确保找到的索引有效
    if (previewIndex.value >= 0) {
      imageViewerVisible.value = true;
    } else {
      ElMessage.warning('Unable to locate the preview image');
    }
  }
  const handleExceed = () => {
    ElMessage.warning('Remote control instructions can only upload one image');
  };
  const handleImageChange = async (file, fileList) => {
    try {
      if (!currentModelData.value) return false;
      
      const isImage = file.raw.type.startsWith('image/');
      const isLt5M = file.raw.size / 1024 / 1024 < 1; 
      
      if (!isImage) {
        ElMessage.error('Only image files can be uploaded!');
        return false;
      }
      if (!isLt5M) {
        ElMessage.error('The size of the picture should not exceed 1MB!');
        return false;
      }

      // 生成预览URL
      file.url = URL.createObjectURL(file.raw);
      currentModelData.value.imageFiles = fileList;
      imagePreviews.value = fileList.map(item => item.url);

      showLoading("Compressing image...")
      const compressedFile = await compressImg(file.raw);
      hideLoading()
      showLoading("Uploading image...")
      const formData = new FormData();
      formData.append('multipartFile', compressedFile);
      formData.append('fileName',`${Date.now()}.jpg`);
      
    
      const res = await axios.post(`${BASE_URL}upload/file`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      if (res.data.code === 0) {
        
        const url = res.data.data.url;
        const key = res.data.data.key;
        const updatedFileList = fileList.map(f => 
          f.uid === file.uid ? { ...f, url, key,status: 'success' } : f
        );
        currentModelData.value.imageFiles = updatedFileList;
        imagePreviews.value = updatedFileList.map(item => item.url);
        return true;
      } else {
        ElMessage.error('The picture upload failed. Please try again');
        return false;
      }
    } catch (error) {
      ElMessage.error(`The picture upload failed: ${error.message}`);
    } finally {
      hideLoading()
    }
  };
  //图片删除
  const handleImageRemove = async(file, fileList) => {
    if (!currentModelData.value) return
    try{
      showLoading("Deleting image...")
      if(file.key) {
        await axios.post(`${BASE_URL}file/del`,null,{
          params: {
            fileKey: file.key
          }
        })
      }
      if(file.url?.startsWith('blob:')){
        URL.revokeObjectURL(file.url)
      }
      currentModelData.value.imageFiles = fileList.filter(item => item.uid !== file.uid)
      imagePreviews.value = fileList.map(item => item.url)
      ElMessage.success('The picture has been deleted successfully.')
    } catch(error) {
      ElMessage.error(`Deletion failed: ${error.response?.data?.msg}`);
    } finally {
      hideLoading()
    }
  }

  // 处理视频上传
  const handleVideoChange = async(file) => {
    try {
      if (!currentModelData.value) return
    
      const isVideo = file.raw.type.startsWith('video/')
      const isLt10M = file.raw.size / 1024 / 1024 < 10 // 限制10MB
      
      if (!isVideo) {
        ElMessage.error('Only video files can be uploaded.!')
        return
      }
      if (!isLt10M) {
        ElMessage.error('The video size cannot exceed 10MB.!')
        return
      }
      
      // 如果已有视频，先删除旧的
      if (currentModelData.value.videoFile) {
        handleVideoRemove()
      }
      showLoading("uploading video...")
      // currentModelData.value.videoFile = file.raw
      // currentModelData.value.videoPreviewUrl = URL.createObjectURL(file.raw)

        const formData = new FormData();
      formData.append('multipartFile', file.raw);
      formData.append('fileName',`${Date.now()}.mp4`);

        const res = await axios.post(`${BASE_URL}upload/file`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        const data = res.data
        if(data.code === 0) {
          const url = data.data.url;
          const key = data.data.key;
          currentModelData.value.videoPreviewUrl = url
          currentModelData.value.key = key
        } else {
          ElMessage.error(response.data.msg + 'Upload failed. Please try again.');
      }
    } catch(error) {
      ElMessage.error('Video upload failed: ' + error.msg);
    } finally {
      hideLoading()
    }
  }

  // 移除视频
  const handleVideoRemove = async() => {
    if (!currentModelData.value) return
    const key = currentModelData.value.key
    showLoading('deleting video...')
    try{
      await axios.post(`${BASE_URL}file/del`, null, {
        params: { fileKey: key }
      })
      currentModelData.value.videoFile = null
      currentModelData.value.videoPreviewUrl = ''
      currentModelData.value.videoUrl = ''
      currentModelData.value.key = ''

      ElMessage.success('Video deleted successfully')
    } catch (err) {
      ElMessage.error(err.response?.data?.msg || 'Failed to delete video')
    } finally {
      hideLoading();
    }
  }

</script>

<style scoped>
  .parent {
      position: absolute;
      display: flex;
      margin-top: -80px;
      width: 97%;
      background-color:white;
      color: black;
      z-index: 11;
      flex-direction: column;
      height: 100vh;
      overflow: hidden;
    }
    /* 返回按钮 */
    .back {
      position: relative;
      height: 70px;
      width: 100%;
    }
    .icon-close {
      position: absolute;
      right: 20px;
      top:5px;
      width: 80px;
      height: 40px;
      border: none !important;
      background-color: transparent !important;
      padding: 8px; /* 适当增加点击区域 */
      transition: all 0.3s ease; /* 添加过渡动画 */
    }
    .icon-close:hover {
      background-color: #f56c6c !important; /* Element UI 的 danger 红色 */
      border-radius: 4px; /* 添加圆角 */
    }
    .icon-close:hover .el-icon {
      color: white !important;
    }
    .el-icon {
      color: #606266; 
      font-size: 29px;
    }

    /* 屏幕滚动条 */
    .information-scroll {
      flex: 1;
    }
    .information {
      margin-bottom: 200px;
    }
    /* 数据栏样式 */
    .text-label {
      font-family: 'Franklin Gothic Medium';
      font-size: 20px;
      color: #557cb7;
      padding-right: 8px;
    }
    .text-border1 {
      display: flex;
      box-sizing: border-box;
      margin-bottom: 23px;
    }
    .text1 {
      width: 350px;
      height: 50px;
      text-align: left;
      border-radius: 12px;
      font-size: 18px;
      color: #464951;
      margin: 0 15px;
      padding: 0 20px;
      line-height: 50px;
      border: 1px solid #E2E8F0;
      box-sizing: border-box; 
      white-space: nowrap;       /* 禁止换行 */
      cursor: not-allowed; /* 显示不可操作光标 */
      user-select: none; /* 禁止文本选择 */
      background-color: rgba(240, 240, 240, 0.9);
    }

    .text-border2 {
      display: flex;
      width: 95%;
      height: 50px;
      overflow: hidden;
      box-sizing: border-box;
      padding: 0 20px;
      align-items: center;
      margin-bottom: 23px;
      box-sizing: border-box;
    }
    :deep(.text-border2 .el-button) {
      flex: 1;
      height: 50px;
      margin: 0 40px;
      font-size: 20px;
      border-radius: 8px;
    }
    .title-input {
      height: 50px;
      flex: 1;
      margin-left: 10px;
      font-size: 18px;
    }
    .text-border3 {
      display: flex;
      width: 95%;
      overflow: hidden;
      box-sizing: border-box;
      padding: 0 20px;
      margin-bottom: 23px;
    }
    .content-input {
      flex: 1;
      margin-left: 10px;
      font-size: 17px;
    }

    .text-border4 {
      display: flex;
      width: 95%;
      min-height: 200px;
      font-size: 18px;
      border-radius: 12px;
      box-sizing: border-box;
      margin-bottom: 23px;
      border: 1px solid #E2E8F0;
      padding: 10px;
    }
    .images-wrapper {
      margin-left: 10px;
      flex: 1;
      flex-wrap: wrap;
      justify-content: flex-start;
      align-items: flex-start;
    }
    /* Element Plus样式 */
    :deep(.el-upload-list--picture-card) {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
    }
    /* 上传组件样式调整 */
    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      width: 180px;
      height: 180px;
      transition: all 0.3s ease;
      border: none;
    }
    :deep(.el-upload--picture-card) {
      width: 180px;
      height: 180px;
      transition: all 0.3s ease;
    }
    :deep(.el-upload-list--picture-card .el-upload-list__item:hover) {
      transform: scale(1.05);
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    /* 所有操作图标 */
    :deep(.el-upload-list--picture-card .el-upload-list__item-actions .el-icon) {
      font-size: 40px;
      color: white;
    }
    /* 鼠标悬停效果 */
    :deep(.el-upload-list--picture-card .el-upload-list__item-actions .el-icon:hover) {
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
    }

    /* 视频样式 */
    .text-border5 {
      display: flex;
      width: 95%;
      min-height: 200px;
      border-radius: 12px;
      box-sizing: border-box;
      margin-bottom: 23px;
      border: 1px solid #E2E8F0;
      padding: 10px;
    }
    .video-wrapper {
      margin-left: 17px;
    }
    .video-button {
      position: relative;
      height: 180px;
      width: 180px;
      background-color: rgb(250,250,250);
      color: #464951;
      font-size: 18px;
      border: 1px dashed rgb(208,208,208);
    }
    .video-button:hover {
      border: 1px dashed rgb(64,158,255);
      color: rgb(64,158,255);
    }
    .video-preview-container {
      display: flex;
      flex-direction: column;
      gap: 10px;
      max-width: 600px;
    }
    .video-preview {
      width: 100%;
      max-height: 400px;
      border-radius: 8px;
      background-color: #000;
    }
    .video-actions {
      display: flex;
      gap: 10px;
    }
    /* 响应式调整 */
    @media (max-width: 768px) {
      .video-preview {
        max-height: 300px;
      }
      .video-actions {
        flex-direction: column;
      }
    }
    .video-disabled-tip {
      padding: 10px;
      color: #909399;
      font-size: 16px;
      text-align: center;
      border: 1px dashed #dcdfe6;
      border-radius: 6px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 180px;
      width: 180px;
      box-sizing: border-box;
    }

    .video-disabled-tip .el-icon {
      font-size: 40px;
      color: #c0c4cc;
    }

  .active {
    background-color: #409eff;
    color: white;
  }

  .no-data-tip {
    padding: 20px;
    text-align: center;
    color: #909399;
    font-size: 16px;
  }
  .text-border6 {
    display: flex;
    gap: 20px; /* 按钮间距 */
    justify-content: center;
    margin-top: 20px;
  }
</style>